package com.example.cart.service.impl;

import com.example.cart.mapper.UserMapper;
import com.example.cart.model.User;
import com.example.cart.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service("UserService")
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisTemplate<Object, Object> redisTemplate;

    @Override
    public User login(User user){
        return  userMapper.selectByUsernameAndPasswordAndRole(user.getUsername(),user.getPassword());
    }

    @Override
    public void saveUser(String token, User user) {
        // 设置redisTemplate对象key的序列化方式
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        // key是token，value是用户保存到redis中，超时时间1小时
        redisTemplate.opsForValue().set(token, user, 1, TimeUnit.HOURS);
    }

    @Override
    public Integer register(String username,String password){
        User temp = userMapper.selectByUsername(username);
        if(temp != null) return 0;
        User user = new User(username,password);
        user.setRole("guest");
        return userMapper.insertSelective(user);
    }

    @Override
    public void setPassword(Integer id,String newpassword){
        User user = new User();
        user.setId(id);
        user.setPassword(newpassword);
        userMapper.updateByPKSelective(user);
    }

    @Override
    public List<User> getAll(){ return userMapper.selectAll();}

    @Override
    public Integer getSearchCount(Map<String,Object> params){ return userMapper.selectCountBySearch(params);}

    @Override
    public List<User> searchUsersByPage(Map<String,Object> params){ return userMapper.selectBySearch(params);}


    @Override
    public Integer add(User user){ return userMapper.insertSelective(user); }

    @Override
    public Integer delete(User user){
        if(user.getId() == 1)
            return 0;
        return userMapper.deleteByPK(user.getId());
    }

    @Override
    public Integer update(User user){ return userMapper.updateByPKSelective(user);}
}
